
import React from 'react';

import './Cart.css' ;

import CartItem from './CartItem';

class Cart extends React.Component {
    constructor(){
        super();
        // 初始化状态
        this.state = {
            items: [
                { id: 1234, name: '中兴 Axon 40 Ultra', price: 7298, amount: 1 },
                { id: 2233, name: '小米MIX Alpha', price: 19999, amount: 1 },
                { id: 3344, name: '红魔7Pro', price: 5699, amount: 2 }
            ]
        }
        // 为函数绑定 this 
        this.handleDecrease = this.handleDecrease.bind( this );
        this.handleIncrease = this.handleIncrease.bind( this );
        this.handleRemove = this.handleRemove.bind( this );
    }
    render(){
        return (
            <div className="cart">
                { 
                    this.state.items.map( (item,index) => {
                        return (
                            <CartItem key={ item.id } 
                                      ordinal={ index + 1 } 
                                      item={ item }
                                      decrease={ this.handleDecrease }
                                      increase={ this.handleIncrease }
                                      remove={ this.handleRemove }>
                            </CartItem>
                        )
                    }) 
                }
            </div>
        )
    }
    // 定义一个函数，将来通过 attribute 传递给子组件
    handleRemove( id ){
        console.log( '接收到的id是' , id );
        // 获得数据
        let array = this.state.items ;
        let index = array.findIndex( item => item.id === id );
        if( index !== -1 ){
            array.splice( index , 1 );
            // 更改状态
            this.setState( { items: array } );
        }
    }
    handleDecrease( id ){
        console.log( '接收到的id是' , id );
        // 获得数据
        let array = this.state.items ;
        let item = array.find( item => item.id === id );
        if( item && item.amount > 1 ){
            item.amount--;
            // 更改状态
            this.setState( { items: array } );
        }
    }
    handleIncrease( id ){
        console.log( '接收到的id是' , id );
        // 获得数据
        let array = this.state.items ;
        let item = array.find( item => item.id === id );
        if( item ){
            item.amount++;
            // 更改状态
            this.setState( { items: array } );
        }
    }
}

export default Cart ;